package com.koi.common.utils.number;

import java.util.Random;

/**
 * @author ･ᴗ･
 * @description [验证码工具类]
 */
public class VerifyCodeUtil {

    public static final String NUMBER = "0123456789";

    public static final String COMMON_LETTERS = "123456789ABCDEFGHJKLMNOPQRSTUVWXYZ";

    public static final String CAPITAL_LETTER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String LOWERCASE_LETTER = "abcdefghijklmnopqrstuvwxyz";

    public static final String MIXED_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";


    /**
     * @param verifySize 验证码长度
     * @description [生成验证码]
     */
    public static String generateCode(int verifySize) {
        return generateVerifyCode(verifySize, COMMON_LETTERS);
    }

    /**
     * @param verifySize 验证码长度
     * @description [生成数字验证码]
     */
    public static String generateNumber(int verifySize) {
        return generateVerifyCode(verifySize, NUMBER);
    }

    /**
     * @param verifySize 验证码长度
     * @description [生成字大写母验证码]
     */
    public static String generateCapitalLetter(int verifySize) {
        return generateVerifyCode(verifySize, CAPITAL_LETTER);
    }

    /**
     * @param verifySize 验证码长度
     * @description [生成小写字母验证码]
     */
    public static String generateLowercaseLetter(int verifySize) {
        return generateVerifyCode(verifySize, LOWERCASE_LETTER);
    }

    /**
     * @param verifySize 验证码长度
     * @description [生成数字 和 字母混合验证码]
     */
    public static String generateMixedLetters(int verifySize) {
        return generateVerifyCode(verifySize, MIXED_LETTERS);
    }

    /**
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @description [使用指定源生成验证码]
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = MIXED_LETTERS;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    public static void main(String[] args) {
        System.out.println("验证码：" + VerifyCodeUtil.generateCode(4));
        System.out.println("数字：" + VerifyCodeUtil.generateNumber(6));
        System.out.println("大写字母：" + VerifyCodeUtil.generateCapitalLetter(6));
        System.out.println("小写字母：" + VerifyCodeUtil.generateLowercaseLetter(6));
        System.out.println("混合：" + VerifyCodeUtil.generateMixedLetters(6));
    }

}
